package com.xiliubit.cloudpicture.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.xiliubit.cloudpicture.config.CosClientConfig;
import com.xiliubit.cloudpicture.exception.BusinessException;
import com.xiliubit.cloudpicture.exception.ErrorCode;
import com.xiliubit.cloudpicture.manager.CosManager;
import com.xiliubit.cloudpicture.model.dto.file.PictureUploadResult;
import com.xiliubit.cloudpicture.utils.ColorTransformUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
@Slf4j
public abstract class PictureUploadTemplate {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;


    /**
     * 上传图片
     *
     * @param inputSource 图片源
     * @param uploadPathPrefix 上传路径前缀
     * @return 图片上传结果
     */
    public  PictureUploadResult putPicture(Object inputSource, String uploadPathPrefix) {
        // 1.校验图片
        // 与第二步合并为返回图片后缀
        String Suffix = validPicture(inputSource);
        // 2. 获取图片地址
//        String originalFilename = multipartFile.getOriginalFilename();
        String originalFilename = getOriginalFilename(inputSource);
        // 获取图片后缀
//        String Suffix = FileUtil.getSuffix(originalFilename);
        String uploadFilename = String.format("%s_%s.%s", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                RandomUtil.randomString(8), Suffix);
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);


        // 文件目录
//        String filepath = String.format("/test/%s", originalFilename);
        // 修复Windows系统下文件名非法字符问题
        String filepath = String.format("/test/%s", RandomUtil.randomString(8));
        File file = null;
        try {
            // 3.创建临时文件
            file = File.createTempFile(filepath, null);
            // 下载图片
//            multipartFile.transferTo(file);
            processFile(inputSource, file);
            // 4.上传图片到对象存储
            PutObjectResult putObjectResult = cosManager.putPictureObject(file, uploadPath);
            List<CIObject> objectList = putObjectResult.getCiUploadResult().getProcessResults().getObjectList();
            if (CollUtil.isNotEmpty(objectList)){
                CIObject webpCIObject = objectList.get(0);
                CIObject thumbnailCIObject = webpCIObject;
                if (objectList.size() > 1) {
                    thumbnailCIObject = objectList.get(1);
                }
                // 5.封装压缩图和缩略图返回结果
                return buildResult(putObjectResult, originalFilename, webpCIObject, thumbnailCIObject);
            }
            // 压缩失败，封装原图信息返回结果
            return buildResult(putObjectResult, originalFilename, uploadPath, file);
        } catch (Exception e) {
            log.error("文件上传失败: {}", uploadPath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            deleteTempFile(file, filepath);
        }

    }

    /**
     * 封装返回结果(压缩图和缩略图)
     *
     * @param originalFilename 原始文件名
     * @param webpCIObject 压缩图
     * @param thumbnailCIObject 缩略图
     * @return 封装结果
     */
    public PictureUploadResult buildResult(PutObjectResult putObjectResult, String originalFilename, CIObject webpCIObject, CIObject thumbnailCIObject) {
        ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();

        // 获取图片信息
        Integer height = webpCIObject.getHeight();
        Integer width = webpCIObject.getWidth();

        // 封装信息
        PictureUploadResult pictureUploadResult = new PictureUploadResult();
        pictureUploadResult.setName(FileUtil.mainName(originalFilename));
        pictureUploadResult.setUrl(cosClientConfig.getHost() + "/" + webpCIObject.getKey());
        pictureUploadResult.setPicFormat(webpCIObject.getFormat());
        pictureUploadResult.setPicSize(webpCIObject.getSize().longValue());
        pictureUploadResult.setPicHeight(height);
        pictureUploadResult.setPicWidth(width);
        pictureUploadResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCIObject.getKey());
        pictureUploadResult.setPicColor(ColorTransformUtils.getStandardColor(imageInfo.getAve()));
        // 这里将整数转化为double，避免精度丢失
        pictureUploadResult.setPicScale(height * 1.0 / width);
        return pictureUploadResult;
    }

    /**
     * 封装返回结果(原图)
     *
     * @param putObjectResult 上传结果
     * @param originalFilename 原始文件名
     * @param uploadPath 上传路径
     * @param file 文件
     * @return 返回结果
     */
    public PictureUploadResult buildResult(PutObjectResult putObjectResult, String originalFilename, String uploadPath, File file) {
        // 获取图片信息
        ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
        int PictureHeight = imageInfo.getHeight();
        int PictureWidth = imageInfo.getWidth();

        // 封装信息
        PictureUploadResult pictureUploadResult = new PictureUploadResult();
        pictureUploadResult.setName(FileUtil.mainName(originalFilename));
        pictureUploadResult.setUrl(cosClientConfig.getHost() + uploadPath);
        pictureUploadResult.setPicFormat(imageInfo.getFormat());
        pictureUploadResult.setPicSize(FileUtil.size(file));
        pictureUploadResult.setPicHeight(PictureHeight);
        pictureUploadResult.setPicWidth(PictureWidth);
        // 这里将整数转化为double，避免精度丢失
        pictureUploadResult.setPicScale(PictureHeight * 1.0 / PictureWidth);
        return pictureUploadResult;
    }

    /**
     * 根据校验图片
     *
     * @param inputSource 图片
     */
    public abstract String validPicture(Object inputSource);


    /**
     * 获取图片名
     *
     * @param inputSource 图片
     * @return 图片名
     */
    public abstract String getOriginalFilename(Object inputSource);

    /**
     * 下载图片到本地作为中转
     *
     * @param inputSource  图片
     * @param file         图片文件
     */
    public abstract void processFile(Object inputSource, File file);

    public static void deleteTempFile(File file, String filepath) {
        if (file != null) {
            // 删除临时文件
            boolean delete = file.delete();
            if (!delete) {
                log.error("临时文件删除失败： {}", filepath);
            }
        }
    }
}
